﻿using PENet;
using System;
using MsgExample;

namespace ServerExample
{
    class ServerSession : KCPSession<NetMsg>
    {
        protected override void OnConnected()
        {
            KCPTool.ColorLog(KCPLogColor.Green, "Client Online,Sid:{0}", m_sid);
        }

        protected override void OnDisConnected()
        {
            KCPTool.Warn("Client OnDisConnected,Sid:{0}", m_sid);
        }

        protected override void OnReciveMsg(NetMsg msg)
        {
            KCPTool.Log($"Sid:{m_sid},Recive:{(msg.cmd==CMD.NetPing?"NetPing":msg.info)}");
            if (msg.cmd == CMD.NetPing)
            {
                if (msg.netPing.isOver)
                {
                    CloseSession();
                }
                else
                {
                    //收到ping请求，则重置检查计数，并回复ping消息到客户端
                    checkCounter = 0;
                    NetMsg pingMsg = new NetMsg
                    {
                        cmd = CMD.NetPing,
                        netPing = new NetPing
                        {
                            isOver = false
                        }
                    };
                    SendMsg(pingMsg);
                }
            }
        }

        private int checkCounter;
        DateTime checkTime = DateTime.UtcNow.AddSeconds(5);
        protected override void OnUpdate(DateTime now)
        {
            if (now > checkTime)
            {
                checkTime = now.AddSeconds(5);
                checkCounter++;
                if (checkCounter > 3)
                {
                    NetMsg pingMsg = new NetMsg
                    {
                        cmd = CMD.NetPing,
                        netPing = new NetPing { isOver = true }//终止服务器session
                    };
                    OnReciveMsg(pingMsg);
                }
            }
        }
    }
}
